<template>
  <div class="login">
    <img src="../assets/images/login_icon.png" alt="" />
    <div class="login_form">
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title">登录</h3>
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" size="small" auto-complete="off" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            :type="pwdInputType"
            size="small"
            auto-complete="off"
            placeholder="请输入密码"
            @keyup.enter="handleLogin"
          >
            <template #suffix
              ><el-icon>
                <Hide v-if="pwdInputType === 'password'" @click="togglePwdView" />
                <View v-else @click="togglePwdView" />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <div style="display: flex">
            <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter="handleLogin">
              <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" />
            </div>
          </div>
        </el-form-item>
        <div class="pwd_line">
          <div class="flex" @click="toggleRememberPwd" style="cursor: pointer;">
            <div class="checked_border">
              <img v-if="rememberPwd" src="../assets/images/login_checked.png" alt="" />
            </div>
            记住密码
          </div>
          <el-button type="text" @click="forgetPassword" style="cursor: pointer;">忘记密码</el-button>
        </div>
        <el-form-item style="width: 100%">
          <el-button class="login_btn" :loading="loading" size="small" type="primary" style="width: 100%" @click.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
        <el-form-item style="width: 100%">
          <div class="rules_line">
            <div class="checked_border" @click="toggleIsArgee"><img v-if="isAgree" src="../assets/images/login_checked.png" alt="" /></div>
            <div @click="toggleIsArgee">
              登录默认阅读并同意<span @click.stop="goRules('yhxy')">《用户协议》</span><span @click.stop="goRules('yszc')">《隐私政策》</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div class="link-type"><router-link :to="'/register'">立即注册</router-link></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const userStore = useUserStore();
const router = useRouter();
// admin
// mima8ge8
const loginForm = ref<LoginData>({
  tenantId: '000000', // 租户id先写死
  username: '',
  password: '',
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
  code: [{ required: true, trigger: 'blur', message: '请输入验证码' }],
};

const pwdInputType = ref('password')
// 密码可见切换
const togglePwdView = () => {
  if (pwdInputType.value === 'password') pwdInputType.value = 'text'
  else pwdInputType.value = 'password'
}

// 注册开关
const redirect = ref(undefined);
const loginRef = ref<ElFormInstance>();

// 是否勾选同意协议
const isAgree = ref(false);
const loading = ref(false);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

//   忘记密码
const forgetPassword = () => {
  console.log('忘记密码')
  router.push('/register?resetPwd=true')
}
const rememberPwd = ref(false)
// 切换记住密码
const toggleRememberPwd = () => {
  rememberPwd.value = !rememberPwd.value
}
// 切换勾选协议
const toggleIsArgee = () => {
  isAgree.value = !(isAgree.value)
}

// 跳转协议页面
const goRules = (cate: string) => {
  router.push({
    path: `/agreementDetail`,
    query: {
      cate
    }
  })
}

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      if (!isAgree.value) return proxy?.$modal.msgError("请先阅读并同意相关协议");
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (rememberPwd.value) {
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberPwd', String(rememberPwd.value));
      } else {
        // 否则移除
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberPwd');
      }
      if (isAgree.value) localStorage.setItem('isAgreeProtocol', String(isAgree.value));
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        await router.push({ path: redirect.value || '/' });
        loading.value = false;
      } else {
        loading.value = false;
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};


const getLoginData = () => {
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberPwd_ = localStorage.getItem('rememberPwd');
  const isAgree_ = localStorage.getItem('isAgreeProtocol');
  loginForm.value = {
    tenantId: '000000',
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
  } as LoginData;
  rememberPwd.value = rememberPwd_ === null ? false : Boolean(rememberPwd_)
  isAgree.value = isAgree_ === null ? false : Boolean(isAgree_)
};

/**
 * 获取验证码
 */
const codeUrl = ref('');
const captchaEnabled = ref(true);

 const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};


onMounted(() => {
  getCode()
  getLoginData();
});
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
  align-items: center;
}
.login {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url('../assets/images/login_bg.jpg');
  background-size: cover;
  overflow: scroll;
  font-size: 16px;
  & > img {
    width: 7.6vw;
    height: auto;
    position: absolute;
    top: 22px;
    left: 32px;
  }
  .login_form {
    position: absolute;
    top: 0;
    right: 0;
    width: 41vw;
    min-height: 100%;
    background: #FFFFFF;
    border-radius: 24px 0px 0px 0px;
    padding-bottom: 48px;
    // display: flex;
    // justify-content: center;
    // align-items: center;

    .login-form {
      // margin: 0 auto;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      .el-form-item {
        margin-bottom: 25px;
      }
      .title {
        text-align: center;
        font-weight: 500;
        font-size: 28px;
        color: #3D3D3D;
      }

      .pwd_line,
      .rules_line {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .checked_border {
          width: 20px;
          height: 20px;
          border: 3px solid #D8D8D8;
          box-sizing: border-box;
          border-radius: 4px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 10px;
          img {
            width: 10px;
            height: 6px;
          }
        }
      }
      .pwd_line {
        font-weight: 400;
        font-size: 16px;
        color: #AAAAAA;
        .el-button {
          font-weight: 400;
          font-size: 16px;
          color: #096AFF;
        }
      }
      .login_btn {
        margin-top: 57px;
        width: 20vw;
        height: 64px;
        background-color: #096AFF;
        border-radius: 8px;
        text-align: center;
        line-height: 64px;
        font-size: 16px;
      }
      .rules_line {
        font-weight: 400;
        font-size: 16px;
        color: #3D3D3D;
        cursor: pointer;
        span {
          color: #096AFF;
        }
      }
    }
    .link-type {
      position: absolute;
      bottom: 48px;
      left: 50%;
      transform: translateX(-50%);
      // text-align: center;
      // margin: 0 auto;
      // margin-top: 241px;
      font-weight: 400;
      font-size: 16px;
      color: #096AFF;
    }

  }
}

.login-form {
  background: #ffffff;
  width: 384px;
  .el-input {
    width: 384px;
    height: 64px;
    :deep(.el-input__wrapper) {
      padding-left: 24px;
      padding-right: 24px;
      background: #F3F5F9 !important;
      border-radius: 8px 8px 8px 8px !important;
      border: none !important;
      input {
        height: 64px;
        font-size: 16px !important;
      }
    }
  }
}
:deep(.el-input__wrapper) {
  background: #F3F5F9 !important;
  border-radius: 8px 8px 8px 8px !important;
  border: none !important;
  box-shadow: none!important;
  input {
    height: 64px;
  }
}
.login-code {
  margin-left: 10px;
}
:deep(.el-input__suffix-inner) {
  font-size: 16px;
}
</style>
